var xlsx = require("node-xlsx");
var fs = require("fs");
var path = require("path");
var zlib = require("zlib");

var allbuf = Buffer.alloc(99999999);
var rooturl = "F:\\UnityTableTool\\tables";
var saveurl = "F:\\UnityTableTool\\out";
var single = [];
if (process.argv.length > 2) {
    if (process.argv.length > 2) {
        rooturl = __dirname + process.argv[2];
    }
    if (process.argv.length > 3) {
        saveurl = __dirname + process.argv[3];
    } else {
        saveurl = __dirname + rooturl;
    }

    if (process.argv.length > 4) {
        for (var i = 4; i < process.argv.length; i++) {
            single.push(process.argv[i]);
        }
    }
}

allbuf.pos = 0;
readDirSync(rooturl, "");
packageData();
function readDirSync(path, tag) {
    var pa = fs.readdirSync(path);
    pa.forEach(function (ele, index) {
        if (ele.indexOf("~$") == 0) return;
        var info = fs.statSync(path + "/" + ele);
        if (info.isDirectory()) {
            // console.log("dir: "+ele)
            if (tag.length > 0) {
                readDirSync(path + "/" + ele, tag + "_" + ele);
            } else {
                readDirSync(path + "/" + ele, ele);
            }
        } else {
            if (ele.slice(ele.lastIndexOf(".") + 1) != "xlsx") return;
            var realName = ele.split(".");
            var newName = tag.length > 0 ? tag + "_" + realName[0] : realName[0];
            console.log("读取", ele, newName)
            var buf = readXlsx(path + "/" + ele, newName);
            if (buf) {
                // console.log("写入文件："+newName,buf.length);
                // writeString(allbuf,newName)
                // allbuf.writeInt32BE(buf.length,allbuf.pos);
                // allbuf.pos+=4;
                allbuf.fill(buf, allbuf.pos);
                allbuf.pos += buf.length;
            }
        }
    });
}
//前2个字节是表名字节数，接着是表名字符串，接着是4个字节代表数据字节数量（2字节的行数+数据），接着2字节是行数
function readXlsx(url, name) {
    var datas = xlsx.parse(url);
    var buffer = Buffer.alloc(99999999);
    buffer.pos = 0;
    for (var i = 0; i < datas.length; i++) {
        var clientFields = [];
        if (!datas[i].data[0]) {
            // console.log("跳过",i,datas[i].data[0])
            break;
        }
        for (var f = 0; f < datas[i].data[0].length; f++) {
            // console.log(i,f,datas[i].data[0][f]);
            var title = (datas[i].data[0][f] + "").toLocaleLowerCase();
            if (title == "c" || title == "s|c") {
                clientFields.push(f);
            }
        }
        var rows = datas[i].data.length - 4;
        if (clientFields.length > 0 && rows > 0) {
            writeString(buffer, name + "_" + (i + 1));
            var lenpos = buffer.pos;
            buffer.pos += 6;
            var isOver = false;
            for (var j = 4; j < datas[i].data.length; j++)//第五行开始读取
            {
                for (var k = 0; k < clientFields.length; k++) {
                    var data = datas[i].data[j][clientFields[k]];
                    var type = datas[i].data[1][clientFields[k]] + "";
                    if (k == 0 && (data == undefined || data == null))//可读取的第一个字段为空时就认定为数据行结束
                    {
                        isOver = true;
                        rows = j - 4;
                        break;
                    }
                    try {
                        switch (type.toLocaleLowerCase()) {
                            case "int":
                                buffer.writeInt32BE(Number(data), buffer.pos);
                                buffer.pos += 4;
                                break;
                            case "short":
                                buffer.writeInt16BE(Number(data), buffer.pos);
                                buffer.pos += 2;
                                break;
                            case "byte":
                                buffer.writeUInt8(Number(data), buffer.pos);
                                buffer.pos += 1;
                                break;
                            case "float":
                                buffer.writeFloatBE(Number(data), buffer.pos);
                                buffer.pos += 4;
                                break;
                            case "string":
                                if (data) {
                                    data = data + "";
                                } else if (data === 0) {//支持字符串填0
                                    data = "0";
                                } else {
                                    data = "";
                                }
                                writeString(buffer, data);
                                break;
                        }
                    } catch (e) {
                        console.error("字段错误：" + e);
                        console.log("第" + (i + 1) + "页签", "第" + (j + 1) + "行", "第" + (clientFields[k] + 1) + "列")
                    }

                }
                if (isOver) {
                    break;
                }
            }
            buffer.writeInt16BE(rows, lenpos + 4);
            buffer.writeInt32BE(buffer.pos - lenpos - 4, lenpos);
            console.log(name + "_" + (i + 1) + "  字节长度:" + buffer.pos + "行数:" + rows + " 字段数：" + clientFields.length);
        }
    }
    if (buffer.pos > 0) {
        return buffer.slice(0, buffer.pos);
    }
    return null;
}

function packageData() {
    // zlib.deflate(allbuf.slice(0, allbuf.pos), function (err, buffer) {
    //     if (!err) {
    //         fs.writeFile(saveurl + "/all.data", buffer, function (err) {
    //             if (!err) {
    //                 console.log("打包成功！")
    //             } else {
    //                 console.log("打包失败!");
    //                 console.log(err);
    //             }
    //         });
    //     }
    // });
    fs.writeFile(saveurl + "/all.data", allbuf.slice(0, allbuf.pos), function (err) {
        if (!err) {
            console.log("打包成功！")
        } else {
            console.log("打包失败!");
            console.log(err);
        }
    });
}

function writeString(buf, data) {
    var len = Buffer.byteLength(data);
    // console.log("字符串："+data,"长度："+len,buf.pos);
    buf.writeInt16BE(len, buf.pos);
    buf.pos += 2;
    buf.write(data, buf.pos);
    buf.pos += len;
}